package com.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.commons.PageInfo;

import vo.Book;

public class BookDaoImpl extends BaseDao implements BookDao {

	@Override
	public void save(Book book) {
		this.executeSql("insert into tb_Book values(null,?,?)",book.getBookname(),book.getPrice());

	}

	

	@Override
	public void delete(Integer isbn) {
		this.executeSql("delete from tb_Book where isbn=?", isbn);
		
	}
	
	
	//将List<Map<String,Object>>转换成List<Book>
	private List<Book> convert(List<Map<String,Object>> list){
		List<Book> blist=new ArrayList<Book>();
		for(Map<String,Object> map:list) {
			Book b=new Book();
			//b.setIsbn((Integer)map.get("isbn"));
			b.setIsbn(((Number)map.get("isbn")).intValue());
			b.setBookname(map.get("bookname").toString());
			b.setPrice((Integer)map.get("price"));
			//b.setPrice(((Number)map.get("price")).intValue());
			blist.add(b);
		}

		
		return blist;
	}

	@Override
	public List<Book> getAllByKey(String key) {
		//模糊查询
		return this.convert(this.executeQuery("select isbn,bookname,price from tb_Book where bookname like '%"+key+"%'"));
	}

	@Override
	public Book getBookById(Integer isbn) {
		List<Book> list=this.convert(this.executeQuery("select isbn,bookname,price from tb_Book where isbn=?", isbn));
		Book book=new Book();
		for(Book b:list) {
			book=b;
		}
		return book;

	}

	@Override
	public void update(Book book) {
		this.executeSql("update tb_Book set bookname=?,price=? where isbn=?", book.getBookname(),book.getPrice(),book.getIsbn());
				
	}

	@Override
	public void getAll(PageInfo info) {
		//查询记录总数
		int count=0;
		Connection conn=this.getConnection();
		PreparedStatement ps=null;
		 ResultSet rs=null;
		try {
			ps=conn.prepareStatement("select count(*) from tb_Book");
			rs=ps.executeQuery();
			while(rs.next()) {
				count=((Long)rs.getLong(1)).intValue();
			}
		}catch(Exception e) {
			e.printStackTrace(); 
		}finally {
			this.close(rs);
			this.close(ps);
			this.close(conn);
		}
		info.setRecordCount(count);
		//查询当页数据
		List<Book> list=this.convert(this.executeQuery("select * from tb_Book order by isbn limit ?,?",(info.getCurrentPage()-1)*info.getPageSize(),info.getPageSize()));
		info.setList(list);
	}



	@Override
	public void delete(Integer[] isbn) {
		StringBuffer sb=new StringBuffer("(");
		for(int i=0;i<isbn.length;i++) {
			if(i!=isbn.length-1) { 
			sb.append("?,");
			}else {
				sb.append("?)");
			}
		}
		String sql="delete from tb_Book where isbn in"+sb.toString();
		this.executeSql(sql, isbn);
	}

}